package com.example.online.music.controller;

import com.example.online.music.common.R;
import com.example.online.music.common.RandomCodeGenerate;
import com.example.online.music.constant.Constants;
import com.example.online.music.model.domain.Consumer;
import com.example.online.music.model.request.ConsumerPhoneCodeRequest;
import com.example.online.music.security.model.Result;
import com.example.online.music.security.utils.JwtUtils;
import com.example.online.music.service.ConsumerService;
import com.example.online.music.service.LoginService;
import me.zhyd.oauth.config.AuthConfig;
import me.zhyd.oauth.model.AuthCallback;
import me.zhyd.oauth.request.AuthAlipayRequest;
import me.zhyd.oauth.request.AuthRequest;
import me.zhyd.oauth.utils.AuthStateUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.DigestUtils;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;
import java.nio.charset.StandardCharsets;
import java.security.NoSuchAlgorithmException;


/**
 * 短信验证登录、微信扫码、支付宝扫码、人脸识别接口api
 */
@RestController
@RequestMapping("/login")
@CrossOrigin(origins = "*", maxAge = 3600)
public class ConsumerLoginController {

    @Autowired
    private LoginService loginService;

    @Autowired
    private ConsumerService consumerService;

    /**
     * 发送验证码
     *
     * @param phone
     */
    @PostMapping("/sms")
    public R sendSmsCode(@RequestParam String phone) {
        return loginService.sendRCode(phone);
    }

    /**
     * 校验验证码
     *
     * @param codeRequest
     * @return
     */
    @PostMapping("/sms/code")
    public R checkSmsCode(@RequestBody ConsumerPhoneCodeRequest codeRequest) {
        return loginService.checkRCode(codeRequest);
    }

    /**
     * 支付宝用户授权
     *
     * @param response
     * @throws IOException
     */
    @GetMapping("/render")
    public void renderAuth(HttpServletResponse response) throws IOException {
        AuthRequest authRequest = getAuthRequest();
        response.sendRedirect(authRequest.authorize(AuthStateUtils.createState()));
    }

    @RequestMapping("/callback")
    public Object callback(AuthCallback callback) {
        AuthRequest authRequest = getAuthRequest();
        return authRequest.login(callback);
    }

    private AuthRequest getAuthRequest() {
        return new AuthAlipayRequest(AuthConfig.builder()
                .clientId("2021004101687293")
                .clientSecret("MIIEwAIBADANBgkqhkiG9w0BAQEFAASCBKowggSmAgEAAoIBAQD1/MBs0K7PKbZmdjdZtROqKLbaHh9CeB6XXzJb18pwRa8r4EC1rtINlAMy+m7jy7OpbXJtlA3MijMbFZnKc0Auq7nkjuZDmPsvh+tXawrfsvNI6/CvCLXnBclAQwu+qdv+tGy90oWKiXpxTZbMGb1gYyvSukFvcfAaW++vLpjFbOf+daYuPN33+UPp3TBywe67MvG33+sSSmo4nYN8DZV2n0NJU18Qtr2wDnQ22Tnh7ZjZXooxh5OEFPa8cIUk5o/DjGRu++ip3scJB0v7ZrVSavCw6wBl+TVbjz+qfNzWntp9TQIaa1+Kz5BBEqYd0UIXYpc1PpJJjQnzedKpo4ZFAgMBAAECggEBAJWmBHKuqgqB9+Nxu86paKM2Tbd4Z9AKP6IbWgmhyBhxbFYnAXcGOefkyeVzkY6n2E8UtG6RiauLz/eENqGBZ+R8uIShotgw829BIx11k5Hvzi3oy+3QQMmhLYQYxcZik+HqZdU9g9x6MrFHYJwedKV0764tfa2NBWMj1zceA/bmTw+l/iKm6/O2QX9Oez7RA5bNjy7AMK77zcIKQZuXsRD/SQ1O60h6Vlb5vW1pabx66ou2f6jcv81rYmKhslHVkXXZpFDwr7BJvLGMGuik3onQXkWG3e04Q60Q79x9RG8JPRQPnipSMncyZ7NcH3cG50SewjYl73PO8MMdlIrixMECgYEA+5KH81061i/lgk1tf6LpwliRZpVwseLN8DnREe7q6gT34iF+kRoLNkZe+7TRMyT6HmdVdsPbr216+iHhjdMuAo/i9nfrDK+PDPdPG31brFdWp5xdLK+ISo7Qfk9ZT8sYJlfsr7pTPKzhsRsJOgcwT4h2b7WW812aogDLyd0C/rkCgYEA+lEOjI6IRiZY1koBXSB2ktZ7VuRwR7BqBKlPoxHsaL1T8koA2RAMONNpMrs8YzZNIfmFmzIBkRdQIpoyyDFstnqXrmNrARWKIzjRRDMZpDHHen73VpUNJNyP7annH+n8VVB0r/QXzBlkx8czo/soab7ZAH4TBM9EzswMt/u43e0CgYEApLU/RVrY1rrtLO68rkBfg9qw99UHv6+a3Zk9BNzD+Qvfr7H2R9IhXRudvHaaMT4YdCd7kRKSlry7M2FTZ6PID+1cz7mbruaSZg7VQE5G4wMbvQlnB4a1WPtADjKtasyxtwkB8duv+53E9kuZMuDaBHh38pOVjSjPwRl8U2HcQCECgYEAshQ4ZYaBLGbbjJfZoIcX1B8CYC7kMhwvUGGjZj+6EEmhDx3WvJXOHB9LF+xcabiX5zO8+Uv6EV6kg/lvZzzCOo+8mTPhTEQmoigpuHsiIs3HPD5XeCFR2IeRXWMiKnIsMgWq/gKJa4olSHtPIbnsZk5/0vneTe2m5fgElF9ghYECgYEAphtPaPVdZ1lFzk5JItECw97MksDcTy4UtkoYpvjb6ly15z7Og0cHJflc8dx4wPN6HIArpef/PJzZOOfPGdRJR87dkZmfMf8neqEbBqWvp91hUk+Nx0HPq9HTRv90sUWNeM7zkFtK2t1OtGB2wEvE7G2ky4WqGl8gvobWRTV3qP0=")
                .alipayPublicKey("MIIBIjANBgkqhkiG9w0BAQEFAAOCAQ8AMIIBCgKCAQEAtH9z3Wv/7fspfbvWryn5LBcyAqKBssX873eC4WGlrrL1uOTEAVnFlrYV6Qz0AssjntjNVDPUbdFNZT0hgrvdj4kJrX5uQenNFQ8XzT5D03Lq1G6lDhGOJ2/I7H/8TYUdVpcx9qTOnE1W1bjhsGZ1weBqSBRR5bHg3RzBQ5lzpEfAN24AeWJRU2bHW+tWBjm3ggkjpWvHnrq1gEJY8l903hVzvnvVXNlyVub+aH0pkREczb2e2ZxewxtpDjWJC3LUIedLnoSo9f9am6m7itOoEaeZ5VcrkFGEzZRBNNad1YU3v0JACph7EqSmFkv7xFckvda2S7Z8XIuC1qFOSGBShwIDAQAB")
                .redirectUri("http://9i8hrv.natappfree.cc/login/callback")
                .build());
    }

    /**
     * 发送邮箱验证码
     */
    @PostMapping("/mail/code")
    public R mailLoginCheck(@RequestParam String email) throws NoSuchAlgorithmException {
        //todo 先校验是否已注册,如果没有注册则启动自动注册流程
        //校验是否为注册用户
        String activationCode = String.valueOf(RandomCodeGenerate.createCode(6));
        String message = "邮箱验证码已发送!";
        if (!consumerService.existUserByEmail(email)) {
            Consumer consumer = new Consumer();
            consumer.setUsername(email);
            consumer.setEmail(email);
            consumer.setAvator("https://java-pp.oss-cn-hangzhou.aliyuncs.com/img/avatorImages/user.jpg");
            consumer.setPassword("123456");
            //MD5加密
            String password = DigestUtils.md5DigestAsHex((Constants.SALT + "123456").getBytes(StandardCharsets.UTF_8));
            consumer.setPassword(password);
            //如果不存在，创建用户对象并保存到数据库
            if (consumerService.insert(consumer)) {
                message = "已使用该邮箱自动注册,请查阅邮件后使用验证码登录!";
            } else {
                message = "注册失败,请手动注册!";
            }
        }
        return loginService.sendMailCode(email, activationCode, message);
    }

    /**
     * 验证登录邮箱验证码
     */
    @GetMapping("/mail/activate/{email}/{checkCode}")
    public R checkMailActive(@PathVariable("email") String mail, @PathVariable("checkCode") String code, HttpServletRequest request) {
        if (loginService.checkMailCode(mail, code)) {
            HttpSession session = request.getSession();
            session.setAttribute("username", mail);
            R result = R.success("登录成功");
            String tokenStr = JwtUtils.generateToken(mail);
            Result token = new Result();
            token.setAuthorization(tokenStr);
            Consumer oneByUserName = consumerService.getOneByUserName(mail);
            token.setObj(oneByUserName);
            result.setData(token);
            return result;
        }
        return R.error("邮箱名或者验证码错误!");
    }

}
